import React, { memo ,useEffect,useRef,useState} from 'react'
import { Carousel } from 'antd';
import {  useSelector,useDispatch, shallowEqual } from 'react-redux';

import {getBannerAction} from '../../store/actionCreator'
import { TopBanerWrapper } from "./style";

export default memo(function HjTopBanner() {
  
  // state
    const [bannerCurrentIndex, setBannerCurrentIndex] = useState(0);
  //redux hook
  const dispatch = useDispatch()
  const {banner} = useSelector(state =>({//要返回一个对象
    // banner:state.get('recommend').get('banner')
    banner:state.getIn(['recommend','banner'])
  }),shallowEqual)

  // other hook
  useEffect(() => {
    // 派发action ，一般都是派发对象，这里用redux-thunk,派发函数，在函数里派发action对象，并发异步请求任务保存到redux中。
    dispatch(getBannerAction)
  }, [dispatch]);
  const bannerRef = useRef()

  function bannerChange(from,to) {
    setBannerCurrentIndex(to)
  }

  const bgImg = (banner[bannerCurrentIndex] &&  (banner[bannerCurrentIndex].imageUrl+"?imageView&blur=40x20")) ||""


  return (
    <TopBanerWrapper bgImg={bgImg}>
       <div className="banner wrap-v2" >
         <div className="left">
           <Carousel ref={bannerRef} effect="fade" autoplay beforeChange={bannerChange}>
              {
                banner.map((item,index)=>{
                  return (
                    <div className="item" key={item.imageUrl}>
                        <img src={item.imageUrl} alt=" " />
                    </div>
                  )
                })
              }
           </Carousel>
         </div>
         <div className="right"></div>
         <div className="control">
           <button className="btn btn-left" onClick={e=>bannerRef.current.prev()}></button>
           <button className="btn btn-right" onClick={e=>bannerRef.current.next()}></button>
         </div>
       </div>
    </TopBanerWrapper>
  )
})
